<template>
  <div class="ewe-mating-container">
    <!-- 操作按钮区域 -->
    <div class="operation-bar">
      <div class="left-buttons">
        <el-button type="primary" @click="handleSave">
          <el-icon><Document /></el-icon>
          保存
        </el-button>
        <el-button @click="handleCancel">
          <el-icon><Close /></el-icon>
          取消
        </el-button>
      </div>
    </div>

    <!-- 记录详情区域 -->
    <el-card class="header-card" shadow="never">
      <el-form :model="recordForm" label-width="90px" class="header-form">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="负责人" required>
              <el-select v-model="recordForm.responsiblePerson" placeholder="请选择负责人" filterable style="width: 100%">
                <el-option
                  v-for="user in responsiblePersonOptions"
                  :key="user.value"
                  :label="user.label"
                  :value="user.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="配种日期" required>
              <el-date-picker
                v-model="recordForm.breedingDate"
                type="date"
                placeholder="选择日期"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="单据号">
              <div style="display: flex; align-items: center; gap: 8px;">
                <el-input v-model="recordForm.documentNumber" placeholder="自动生成" readonly />
                <el-button type="primary" size="small" @click="regenerateDocumentNumber">重新生成</el-button>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="流水号">
              <div style="display: flex; align-items: center; gap: 8px;">
                <el-input v-model="recordForm.serialNumber" placeholder="自动生成" readonly />
                <el-button type="primary" size="small" @click="regenerateSerialNumber">重新生成</el-button>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="body-card" shadow="never">
      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        border
        stripe
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="earNumber" label="*耳号" width="120" align="center" required>
          <template #default="scope">
            <el-select
              v-model="scope.row.earNumber"
              placeholder="请选择耳号"
              size="small"
              filterable
              style="width: 100%"
            >
              <el-option
                v-for="item in earNumberList"
                :key="item.Id"
                :label="item.Name"
                :value="item.Id"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="firstBreedingRam" label="*首配公羊" width="120" align="center" required>
          <template #default="scope">
            <el-input
              v-model="scope.row.firstBreedingRam"
              placeholder="请输入首配公羊"
              size="small"
            />
          </template>
        </el-table-column>
        <el-table-column prop="extraMaleSheep" label="补配公羊" width="120" align="center">
          <template #default="scope">
            <el-input
              v-model="scope.row.extraMaleSheep"
              placeholder="请输入补配公羊"
              size="small"
            />
          </template>
        </el-table-column>
        <el-table-column prop="breedingMethod" label="*配种方式" width="120" align="center" required>
          <template #default="scope">
            <el-select
              v-model="scope.row.breedingMethod"
              placeholder="请选择配种方式"
              size="small"
              style="width: 100%"
            >
              <el-option label="自然配种" value="自然配种" />
              <el-option label="人工授精" value="人工授精" />
              <el-option label="胚胎移植" value="胚胎移植" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="eweEstrusType" label="*种母发情类型" width="140" align="center" required>
          <template #default="scope">
            <el-select
              v-model="scope.row.eweEstrusType"
              placeholder="请选择发情类型"
              size="small"
              style="width: 100%"
            >
              <el-option label="自然发情" value="自然发情" />
              <el-option label="人工诱导" value="人工诱导" />
              <el-option label="同期发情" value="同期发情" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="firstBreedingScore" label="首配评分" width="100" align="center">
          <template #default="scope">
            <el-input-number
              v-model="scope.row.firstBreedingScore"
              :min="0"
              :max="10"
              size="small"
              style="width: 80px"
            />
          </template>
        </el-table-column>
        <el-table-column prop="breedingScore" label="配种评分" width="100" align="center">
          <template #default="scope">
            <el-input-number
              v-model="scope.row.breedingScore"
              :min="0"
              :max="10"
              size="small"
              style="width: 80px"
            />
          </template>
        </el-table-column>
        <el-table-column prop="currentBuilding" label="当前栋舍" width="120" align="center">
          <template #default="scope">
            <el-select
              v-model="scope.row.currentBuilding"
              placeholder="请选择栋舍"
              size="small"
              style="width: 100%"
            >
              <el-option
                v-for="item in buildingList"
                :key="item.BuildingId"
                :label="item.House_name"
                :value="item.BuildingId"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="currentPen" label="当前栏位" width="120" align="center">
          <template #default="scope">
            <el-select
              v-model="scope.row.currentPen"
              placeholder="请选择栏位"
              size="small"
              style="width: 100%"
            >
              <el-option
                v-for="item in penList"
                :key="item.Id"
                :label="item.Name"
                :value="item.Id"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="transferBuilding" label="转入栋舍" width="120" align="center">
          <template #default="scope">
            <el-select
              v-model="scope.row.transferBuilding"
              placeholder="请选择栋舍"
              size="small"
              style="width: 100%"
            >
              <el-option
                v-for="item in buildingList"
                :key="item.BuildingId"
                :label="item.House_name"
                :value="item.BuildingId"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="transferPen" label="转入栏位" width="120" align="center">
          <template #default="scope">
            <el-select
              v-model="scope.row.transferPen"
              placeholder="请选择栏位"
              size="small"
              style="width: 100%"
            >
              <el-option
                v-for="item in penList"
                :key="item.Id"
                :label="item.Name"
                :value="item.Id"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="breedingStatus" label="繁殖状态" width="120" align="center">
          <template #default="scope">
            <el-select
              v-model="scope.row.breedingStatus"
              placeholder="请选择状态"
              size="small"
              style="width: 100%"
            >
              <el-option label="待配种" value="待配种" />
              <el-option label="已配种" value="已配种" />
              <el-option label="妊娠中" value="妊娠中" />
              <el-option label="已分娩" value="已分娩" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="eventDate" label="事件日期" width="120" align="center">
          <template #default="scope">
            <el-date-picker
              v-model="scope.row.eventDate"
              type="date"
              placeholder="选择日期"
              value-format="YYYY-MM-DD"
              size="small"
              style="width: 100%"
            />
          </template>
        </el-table-column>
        <el-table-column prop="weight" label="重量(公斤)" width="120" align="center">
          <template #default="scope">
            <el-input-number
              v-model="scope.row.weight"
              :min="0"
              :precision="2"
              size="small"
              style="width: 80px"
            />
          </template>
        </el-table-column>
        <el-table-column prop="femaleBreed" label="种母品种" width="120" align="center">
          <template #default="scope">
            <el-input
              v-model="scope.row.femaleBreed"
              placeholder="请输入种母品种"
              size="small"
            />
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="80" align="center">
          <template #default="scope">
            <el-button link type="danger" size="small" @click="removeRow(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 表格操作按钮 -->
      <div class="table-actions">
        <el-button type="primary" @click="addRow" icon="Plus">+ 增行</el-button>
        <el-button type="danger" @click="removeLastRow" icon="Minus">- 删行</el-button>
      </div>
    </el-card>

    <!-- 合计区域 -->
    <div class="summary-section">
      <span>合计：</span>
      <span>重量：{{ totalWeight.toFixed(2) }} 公斤</span>
    </div>

    <!-- 备注区域 -->
    <el-card class="remark-card" shadow="never">
      <el-form-item label="备注">
        <el-input v-model="recordForm.remarks" type="textarea" placeholder="请输入备注信息" />
      </el-form-item>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Document, Close } from '@element-plus/icons-vue'
import { getEweMatingDetail, addEweMating, updateEweMating } from '../../utils/requestEweMating'
import { Sheep_BreedingRead, serviceRead, Sheep_BreedingWrite } from '../../utils/Interceptors'

// 定义表格行数据类型
interface TableRowData {
  id: string | number;
  earNumber: string | null;
  firstBreedingRam: string;
  extraMaleSheep: string;
  breedingMethod: string;
  eweEstrusType: string;
  firstBreedingScore: string | null;
  breedingScore: number | null;
  currentBuilding: string;
  currentPen: string;
  transferBuilding: string;
  transferPen: string;
  breedingStatus: string;
  eventDate: string;
  weight: number | null;
  femaleBreed: string;
  status: string;
  isEditing: boolean;
}

const route = useRoute()
const router = useRouter()
const loading = ref(false)
const hasChanges = ref(false)
const isEditMode = ref(false) // 新增：是否为编辑模式
const editingBreedingId = ref('') // 新增：正在编辑的记录ID

// 记录表单
const recordForm = reactive({
  responsiblePerson: '',
  breedingDate: '',
  documentNumber: '',
  serialNumber: '',
  remarks: ''
})

// 表格数据
const tableData = ref<TableRowData[]>([
  {
    id: Date.now(),
    earNumber: null,
    firstBreedingRam: '',
    extraMaleSheep: '',
    breedingMethod: '',
    eweEstrusType: '',
    firstBreedingScore: null,
    breedingScore: null,
    currentBuilding: '',
    currentPen: '',
    transferBuilding: '',
    transferPen: '',
    breedingStatus: '',
    eventDate: '',
    weight: null,
    femaleBreed: '',
    status: '待审核',
    isEditing: false
  }
])

// 选项数据
const responsiblePersonOptions = ref<Array<{label: string, value: string}>>([])
const earNumberList = ref<any[]>([])
const buildingList = ref<any[]>([])
const penList = ref<any[]>([])

// 计算总重量
const totalWeight = computed(() => {
  return tableData.value.reduce((sum, row) => {
    return sum + (row.weight || 0)
  }, 0)
})

// 生成单据号
const generateDocumentNumber = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const hours = String(now.getHours()).padStart(2, '0')
  const minutes = String(now.getMinutes()).padStart(2, '0')
  const seconds = String(now.getSeconds()).padStart(2, '0')
  const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0')
  
  return `PZ${year}${month}${day}${hours}${minutes}${seconds}${random}`
}

// 生成流水号
const generateSerialNumber = () => {
  const now = new Date()
  const timestamp = now.getTime()
  const random = Math.floor(Math.random() * 10000).toString().padStart(4, '0')
  
  return `LS${timestamp}${random}`
}

// 重新生成单据号
const regenerateDocumentNumber = () => {
  recordForm.documentNumber = generateDocumentNumber()
  ElMessage.success('单据号已重新生成')
}

// 重新生成流水号
const regenerateSerialNumber = () => {
  recordForm.serialNumber = generateSerialNumber()
  ElMessage.success('流水号已重新生成')
}

// 获取用户列表
const fetchUserList = async () => {
  try {
    const res = await serviceRead.get('/api/User/SraechUser', {
      params: { PageIndex: 1, PageSize: 100 }
    })
    if (res.data && res.data.code === 200 && Array.isArray(res.data.PageData)) {
      responsiblePersonOptions.value = res.data.PageData.map((user: any) => ({
        label: user.UserName,
        value: user.UserName
      }))
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
  }
}

// 获取耳号列表
const fetchEarNumberList = async () => {
  try {
    const res = await Sheep_BreedingRead.get('/api/EliminationInfo/GetSheepFilesIdEarNumber')
    if (res.data && res.data.code === 200 && res.data.data) {
      earNumberList.value = res.data.data || []
    }
  } catch (error) {
    console.error('获取耳号列表失败:', error)
  }
}

// 获取栋舍列表
const fetchBuildingList = async () => {
  try {
    const res = await Sheep_BreedingRead.get('/api/Sheepfarm/SearchBuildingManagement', {
      params: { PageIndex: 1, PageSize: 100 }
    })
    if (res.data && res.data.code === 200 && res.data.PageData) {
      buildingList.value = res.data.PageData || []
    }
  } catch (error) {
    console.error('获取栋舍列表失败:', error)
  }
}

// 获取栏位列表
const fetchPenList = async () => {
  try {
    const res = await Sheep_BreedingRead.get('/api/EliminationInfo/GetFieldManagementIdName')
    if (res.data && res.data.code === 200 && res.data.data) {
      penList.value = res.data.data || []
    }
  } catch (error) {
    console.error('获取栏位列表失败:', error)
  }
}

// 增加行
const addRow = () => {
  tableData.value.push({
    id: Date.now(),
    earNumber: null,
    firstBreedingRam: '',
    extraMaleSheep: '',
    breedingMethod: '',
    eweEstrusType: '',
    firstBreedingScore: null,
    breedingScore: null,
    currentBuilding: '',
    currentPen: '',
    transferBuilding: '',
    transferPen: '',
    breedingStatus: '',
    eventDate: '',
    weight: null,
    femaleBreed: '',
    status: '待审核',
    isEditing: false
  })
  hasChanges.value = true
}

// 删除指定行
const removeRow = (index: number) => {
  if (tableData.value.length > 1) {
    tableData.value.splice(index, 1)
    hasChanges.value = true
  } else {
    ElMessage.warning('至少保留一行')
  }
}

// 删除最后一行
const removeLastRow = () => {
  if (tableData.value.length > 1) {
    tableData.value.pop()
    hasChanges.value = true
  } else {
    ElMessage.warning('至少保留一行')
  }
}

// 保存按钮
const handleSave = async () => {
  if (tableData.value.length === 0) {
    ElMessage.warning('请至少添加一条记录')
    return
  }

  if (!recordForm.responsiblePerson) {
    ElMessage.warning('请选择负责人')
    return
  }

  if (!recordForm.breedingDate) {
    ElMessage.warning('请选择配种日期')
    return
  }

  // 验证表体数据
  for (let i = 0; i < tableData.value.length; i++) {
    const row = tableData.value[i]
    if (!row.earNumber || row.earNumber === '') {
      ElMessage.error(`第${i + 1}行请选择耳号`)
      return
    }
    if (!row.firstBreedingRam) {
      ElMessage.error(`第${i + 1}行首配公羊不能为空`)
      return
    }
    if (!row.breedingMethod) {
      ElMessage.error(`第${i + 1}行配种方式不能为空`)
      return
    }
    if (!row.eweEstrusType) {
      ElMessage.error(`第${i + 1}行种母发情类型不能为空`)
      return
    }
  }

  loading.value = true
  try {
    // 自动生成单据号和流水号
    if (!recordForm.documentNumber) {
      recordForm.documentNumber = generateDocumentNumber()
    }
    if (!recordForm.serialNumber) {
      recordForm.serialNumber = generateSerialNumber()
    }

    // 获取用户信息
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    const userName = userInfo.UserName || '系统用户'
    const currentTime = new Date().toISOString()

    // 只处理第一行数据
    const firstRow = tableData.value[0]
    
    // 生成配种ID或使用现有ID
    const breedingId = isEditMode.value ? editingBreedingId.value : `BID-${new Date().getTime()}-${Math.floor(Math.random() * 1000)}`
    
    // 直接构建DTO对象，不需要包装在dto字段中
    const payload = {
      BreedingId: breedingId,
      BreedingDate: recordForm.breedingDate,
      EarNumber: firstRow.earNumber ? String(firstRow.earNumber) : '',
      FirstMaleSheep: firstRow.firstBreedingRam || '',
      ExtraMaleSheep: firstRow.extraMaleSheep || '',
      BreedingMethod: firstRow.breedingMethod || '',
      FemaleEstrusType: firstRow.eweEstrusType || '',
      FirstBreedingScore: String(firstRow.firstBreedingScore || '0'),
      BreedingScore: Number(firstRow.breedingScore || 0),
      BreedingHouse: String(firstRow.currentBuilding || ''),
      BreedingPen: String(firstRow.currentPen || ''),
      TransferHouse: String(firstRow.transferBuilding || ''),
      BreedingStatus: firstRow.breedingStatus || '已配种',
      EventDate: firstRow.eventDate || recordForm.breedingDate,
      Weight: Number(firstRow.weight || 0),
      FemaleBreed: firstRow.femaleBreed || '默认品种',
      Principal: recordForm.responsiblePerson || '系统',
      Remark: recordForm.remarks || '',
      Creator: userName || '系统',
      Modifier: userName || '系统',
      Auditor: userName || '系统',
      DocumentNo: recordForm.documentNumber || '',
      LastBreedingDate: recordForm.breedingDate, // 上次配种日期默认为当前配种日期
      FemaleType: '种母' // 添加种母类型字段
    }
    
    console.log('准备提交数据:', JSON.stringify(payload))
    
    try {
      let res;
      if (isEditMode.value) {
        // 编辑模式：调用更新API
        console.log('更新现有记录:', editingBreedingId.value)
        res = await updateEweMating(payload)
      } else {
        // 新增模式：调用添加API
        console.log('添加新记录')
        res = await addEweMating(payload)
      }
      
      console.log('API响应:', res)
      
      if (res.data && res.data.code === 200) {
        ElMessage.success(isEditMode.value ? '更新成功' : '保存成功')
        hasChanges.value = false
        router.push('/EweMatingList')
      } else {
        ElMessage.error(res.data?.msg || (isEditMode.value ? '更新失败' : '保存失败'))
        console.error('操作失败详情:', res.data)
      }
    } catch (error: any) {
      console.error('请求异常:', error)
      console.error('请求异常详情:', error.response?.data)
      console.error('请求状态码:', error.response?.status)
      console.error('请求错误信息:', error.message)
      ElMessage.error(error?.response?.data?.msg || error?.message || (isEditMode.value ? '更新失败' : '保存失败'))
    }
  } finally {
    loading.value = false
  }
}

// 取消按钮
const handleCancel = () => {
  ElMessageBox.confirm('确定要取消编辑吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    router.push('/EweMatingList')
  }).catch(() => {})
}

// 加载记录详情
const loadRecordDetail = async (breedingId: string) => {
  try {
    loading.value = true
    console.log('加载记录详情:', breedingId)
    
    // 调用getEweMatingDetail API获取详情
    const res = await getEweMatingDetail(breedingId)
    
    if (res.data && res.data.code === 200 && res.data.data) {
      const detail = res.data.data
      console.log('获取到的记录详情:', detail)
      
      // 填充表单数据
      recordForm.responsiblePerson = detail.Principal || ''
      recordForm.breedingDate = detail.BreedingDate ? new Date(detail.BreedingDate).toISOString().split('T')[0] : ''
      recordForm.documentNumber = detail.DocumentNo || ''
      recordForm.serialNumber = detail.SerialNumber || generateSerialNumber() // 如果没有流水号则生成一个
      recordForm.remarks = detail.Remark || ''
      
      // 填充表格数据
      const rowData: TableRowData = {
        id: breedingId,
        earNumber: detail.EarNumber || null,
        firstBreedingRam: detail.FirstMaleSheep || '',
        extraMaleSheep: detail.ExtraMaleSheep || '',
        breedingMethod: detail.BreedingMethod || '',
        eweEstrusType: detail.FemaleEstrusType || '',
        firstBreedingScore: detail.FirstBreedingScore ? String(detail.FirstBreedingScore) : null,
        breedingScore: detail.BreedingScore ? Number(detail.BreedingScore) : null,
        currentBuilding: detail.BreedingHouse || '',
        currentPen: detail.BreedingPen || '',
        transferBuilding: detail.TransferHouse || '',
        transferPen: detail.TransferPen || '',
        breedingStatus: detail.BreedingStatus || '',
        eventDate: detail.EventDate ? new Date(detail.EventDate).toISOString().split('T')[0] : '',
        weight: detail.Weight ? Number(detail.Weight) : null,
        femaleBreed: detail.FemaleBreed || '',
        status: '待审核',
        isEditing: true
      }
      
      tableData.value = [rowData]
      
      ElMessage.success('数据加载成功')
    } else {
      console.error('获取记录详情失败:', res.data?.msg || '未知错误')
      ElMessage.error('获取记录详情失败')
    }
  } catch (error) {
    console.error('加载记录详情失败:', error)
    ElMessage.error('加载记录详情失败')
  } finally {
    loading.value = false
  }
}

onMounted(async () => {
  // 检查URL中是否有breedingId参数，如果有则是编辑模式
  const breedingId = route.query.breedingId as string
  if (breedingId) {
    isEditMode.value = true
    editingBreedingId.value = breedingId
    console.log('编辑模式，记录ID:', breedingId)
  } else {
    console.log('新增模式')
  }

  // 设置默认配种日期为今天
  recordForm.breedingDate = new Date().toISOString().split('T')[0]
  
  // 自动生成单据号和流水号
  recordForm.documentNumber = generateDocumentNumber()
  recordForm.serialNumber = generateSerialNumber()
  
  // 加载所有必要的数据
  await Promise.all([
    fetchUserList(),
    fetchEarNumberList(),
    fetchBuildingList(),
    fetchPenList()
  ])
  
  // 如果是编辑模式，加载记录详情
  if (isEditMode.value) {
    await loadRecordDetail(editingBreedingId.value)
  }
})
</script>

<style scoped>
.ewe-mating-container {
  min-height: 100vh;
  background: #f7f8fa;
  padding: 24px;
}

.operation-bar {
  background: white;
  padding: 15px 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.left-buttons {
  display: flex;
  gap: 10px;
}

.header-card {
  margin-bottom: 18px;
}

.header-form {
  padding: 12px 0;
}

.body-card {
  margin-bottom: 12px;
}

.table-actions {
  margin-top: 8px;
  display: flex;
  gap: 8px;
}

.summary-section {
  margin: 12px 0 18px 0;
  font-size: 16px;
  font-weight: 500;
  color: #333;
  display: flex;
  gap: 32px;
}

.remark-card {
  margin-top: 12px;
}

:deep(.el-table th) {
  background-color: #f8f9fa;
  color: #333;
  font-weight: bold;
}

:deep(.el-table td) {
  padding: 8px 0;
}

:deep(.el-input-number .el-input__inner) {
  text-align: center;
}
</style> 